package com.jeeplus.modules.guide.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.PageBean;
import com.jeeplus.common.utils.RedisUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.database.datasource.annotation.DS;
import com.jeeplus.modules.guide.entity.*;
import com.jeeplus.modules.guide.mapper.HisQueueMapper;
import com.jeeplus.modules.guide.mapper.MobileQueueMapper;
import com.jeeplus.modules.guide.model.constant.GuideConstant;
import com.jeeplus.modules.guide.model.domain.AvgPeople;
import com.jeeplus.modules.guide.model.domain.HisQueue;
import com.jeeplus.modules.guide.model.domain.MatterArea;
import com.jeeplus.modules.guide.model.vo.AppointmentRecordOut;
import com.jeeplus.modules.sys.entity.MobileUserQR;
import com.jeeplus.modules.sys.utils.UserUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestHeader;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ClassName: MobileQueueService
 * Function:  对接service
 * Date:      2021/6/11 18:35
 *
 * @author azj
 * version    V1.0
 */
@DS("queuing")
@RequiredArgsConstructor
@Service
@Slf4j
public class MobileQueueService {
    /**
     * 获取点位集合
     *
     * @return
     */
    private final MobileQueueMapper mobileQueueMapper;
    private final AppointmentRecordService appointmentRecordService;
    @Value("${swList}")
    private String swList;
    public List<MobileAreaType> listArea() {
        return mobileQueueMapper.listArea();
    }

    /**
     * 获取点位业务
     *
     * @return
     */
    public List<MobileQueueType> findAreaType(String orgrizeId){
        return mobileQueueMapper.findAreaType(orgrizeId);
    }

    /**
     * 获取点位业务
     *
     * @return
     */
    public List<MobileQueueType> findAreaTypeYY(String orgrizeId){
        return mobileQueueMapper.findAreaTypeYY(orgrizeId);
    }
    /**
     * 获取预约记录
     *
     * @return
     */
    public List<AppointmentRecordOut> findByCardId(String idcard) {
        return appointmentRecordService.queryRecordsByCardId(idcard, null, null, null)
                .stream().map(e -> AppointmentRecordOut.builder()
                        .apptDate(DateUtils.formatDate(e.getApptDate(), DateUtils.PATTERN_YYYYMMDD))
                        .isTicket(e.getIsTicket())
                        .busName(e.getBusName())
                        .orgrizeId(e.getOrgrizeId())
                        .createDate(DateUtils.formatDate(e.getCreateDate(), DateUtils.DEFAULT_PATTERN))
                        .officeName(e.getOfficeName())
                        .timePeriod(e.getTimePeriod())
                        .id(e.getId())
                        .ticketdate(e.getTicketdate())
                        .build()
                ).collect(Collectors.toList());
    }

    /**
     * 获取排队记录
     *
     * @return
     */
    public MobileQueueValue getQueueValue(String number, String orgrizeId, String chars){
        return mobileQueueMapper.getQueueValue(number,orgrizeId,chars);
    }

    /**
     * 获取排队用户信息
     *
     * @return
     */
    public MobileQueueUser findUserByNumber(String number, String orgrizeId){
        return mobileQueueMapper.findUserByNumber(number,orgrizeId);
    }

    /**
     * 获取用户预约业务，生成排队编号
     *
     * @return
     */
    public MobileUserYY checkUserYY(String cardid, String orgrizeId){
        return mobileQueueMapper.checkUserYY(cardid,orgrizeId);
    }

    /**
     * 更新用户预约状态
     *
     * @returnid
     */
    @Transactional(readOnly = false)
    public Integer updateUserYY(String id, String number){
        return mobileQueueMapper.updateUserYY(id,number,DateUtils.formatDate(new Date(), DateUtils.DEFAULT_PATTERN));
    }

    /**
     * 录入用户办理事项
     *
     * @returnid
     */
    @Transactional(readOnly = false)
    public int updateUserQueueMatter(String number, String orgrizeId,String matterId,String matterName){
        return mobileQueueMapper.updateUserQueueMatter(number,orgrizeId,matterId,matterName);
    }

    /**
     * 获取大厅排队记录
     *
     * @returnid
     */
    public List<MobileSWQueue> getSWQueue(String doTime){
        Double key = Math.random()*3;
        if(key <= 1){
            return mobileQueueMapper.getSWQueueA(doTime);
        }else if(key >= 2){
            return mobileQueueMapper.getSWQueueB(doTime);
        }else{
            return mobileQueueMapper.getSWQueueC(doTime);
        }
    }


    /**
     * 查询已取号预约记录
     *
     * @returnid
     */
    public String findYYValue(String id){
        return mobileQueueMapper.findYYValue(id);
    }

    /**
     * 获取南区大厅点位集合
     *
     * @return
     */
    public List<MobileAreaType> listNQ(){
        return mobileQueueMapper.listNQ();
    }

    /**
     * 获取南区大厅等待记录
     *
     * @return
     */
    public List<MobileOtherQueue> getMobileOtherQueue(){
        return mobileQueueMapper.getMobileOtherQueue();
    }

    public List<MobileOtherHQueue> getMobileOtherHQueue(){
        return mobileQueueMapper.getMobileOtherHQueue();
    }

    @Transactional(readOnly = false)
    public int updateOtherHQueue(String id,String timeExpr){
        return mobileQueueMapper.updateOtherHQueue(id,timeExpr);
    }

    /**
     * 获取窗口信息
     * @return
     */
    public List<MobileCounter> getMobileCounter(){
        return mobileQueueMapper.getMobileCounter();
    }
    /**
     * 获取点位信息
     * @return
     */
    public  List<MobileOrgrizeTree> getMobileOrgrizeTree(){

        return mobileQueueMapper.getMobileOrgrizeTree();
    }
    /**
     * 获取业务信息
     * @return
     */
   public List<MobileSerial> getMobileSerial(){

        return mobileQueueMapper.getMobileSerial();
    }

    /**
     * 获取业务信息
     * @return
     */
    public List<MobileManager> getMobileManager(){

        return mobileQueueMapper.getMobileManager();
    }


   public List<MobilePjProject> getMobilePjProject(){
       return mobileQueueMapper.getMobilePjProject();
   }


    public List<MobileAreaType> listAreaValue(){
        return mobileQueueMapper.listAreaValue();
    }

    public List<Map<String,Object>> listTypeValueAll(String areaId){
        List<Map<String, Object>> maplist = new ArrayList<>();
        List<String> list = mobileQueueMapper.listAreaOffice(areaId);
        for(String str : list){
            Map<String,Object> maps = new HashedMap();
            maps.put("name",str);
            maps.put("data",mobileQueueMapper.getListAreaOffice(str));
            maplist.add(maps);
        }
        return maplist;
    }
    public List<Map<String,Object>> listTypeValueById(String areaId){
        List<HashMap<String,String>> list = mobileQueueMapper.listAreaCount(areaId);
        List<Map<String, Object>> maplist = new ArrayList<>();
        List<ListArea> listArea;
        List<String> areaList = new ArrayList<>();
        List<ListArea> aList;
        Boolean flag = false;
        if(list.size() >= 1){
            for(HashMap<String,String> map : list){
                areaList.add(map.get("areaId"));
            }
            listArea = mobileQueueMapper.getListAreaValue(areaList);
            for(HashMap<String,String> map : list){
                if(!swList.contains(map.get("areaId"))){
                    aList = new ArrayList<>();
                    Map<String,Object> maps = new HashedMap();
                    for(ListArea li : listArea){
                        if(map.get("areaId").equals(li.getAreaId())){
                            aList.add(li);
                        }
                    }
                    maps.put("name",map.get("areaName"));
                    maps.put("data",aList);
                    maplist.add(maps);
                }else{
                    flag = true;
                }
            }
            if(flag){
                aList = new ArrayList<>();
                Map<String,Object> maps = new HashedMap();
                maps.put("name","税务局");
                for(ListArea li : listArea){
                    if(swList.contains(li.getAreaId())){
                        aList.add(li);
                    }
                }
                maps.put("data",aList);
                maplist.add(maps);
            }

        }else{
            areaList.add(areaId);
            listArea = mobileQueueMapper.getListAreaValue(areaList);
            Map<String,Object> maps = new HashedMap();
            maps.put("name","全部业务");
            maps.put("data",listArea);
            maplist.add(maps);
        }
        areaList.clear();
        list.clear();
        return maplist;
    }

    public MobileAreaType findUserByNumberOther(String orgrizeId){
       return mobileQueueMapper.findUserByNumberOther(orgrizeId);
    }
    public List<MobileAreaType> listAreaByWS(){
       return mobileQueueMapper.listAreaByWS();
    }

    public List<Map<String,Object>> getListAreaWS(String areaId){
        List<Map<String, Object>> maplist = new ArrayList<>();
        Map<String,Object> maps = new HashedMap();
        maps.put("name","全部业务");
        maps.put("data",mobileQueueMapper.getListAreaWS(areaId,"<br>"));
        maplist.add(maps);
       return maplist;
    }

    public HashMap<String,String> isAreaWS(String areaId){
       return mobileQueueMapper.isAreaWS(areaId);
    }

    public Integer findUserQueue(String typeNumber,String areaId,String idcard){
       return mobileQueueMapper.findUserQueue(typeNumber,areaId,idcard);
    }

    public HashMap<String,String> getBussNumberById(String id){
       return  mobileQueueMapper.getBussNumberById(id);
    }

    public String getWinoValue(String areaId,String number){
       return mobileQueueMapper.getWinoValue(areaId,number);
    }

    @Transactional(readOnly = false)
    public void updateTimeIsNull(){
        mobileQueueMapper.updateTimeIsNull();
    }

    public PageBean<MobileQueueList> getQueueList(Map<String,Object> map){
        PageBean<MobileQueueList> pageBean = new PageBean<>();
        PageHelper.startPage(Integer.parseInt(map.get("pageNo")+""), Integer.parseInt(map.get("pageSize")+""));
        if(null == map.get("orderBy")){
            PageHelper.orderBy(" cometime desc");
        }else{
            PageHelper.orderBy(map.get("orderBy")+"");
        }
        List<MobileQueueList> list = mobileQueueMapper.getQueueList(map);
        PageInfo<MobileQueueList> pageInfo = new PageInfo<>(list);
        pageBean.setCrurentNum(Integer.parseInt(map.get("pageNo")+""));
        pageBean.setPageSize(Integer.parseInt(map.get("pageSize")+""));
        pageBean.setTotalNum((int) pageInfo.getTotal());
        pageBean.setTotalPageSize(pageInfo.getPages());
        pageBean.setDatas(pageInfo.getList());
        return pageBean;
    }

    public PageBean<MobileQueueList> getQueueListByIdcare(Map<String,Object> map){
        PageBean<MobileQueueList> pageBean = new PageBean<>();
        PageHelper.startPage(Integer.parseInt(map.get("pageNo")+""), Integer.parseInt(map.get("pageSize")+""));
        if(null == map.get("orderBy")){
            PageHelper.orderBy(" cometime desc");
        }else{
            PageHelper.orderBy(map.get("orderBy")+"");
        }
        List<MobileQueueList> list = mobileQueueMapper.getQueueListByIdcare(map);
        PageInfo<MobileQueueList> pageInfo = new PageInfo<>(list);
        pageBean.setCrurentNum(Integer.parseInt(map.get("pageNo")+""));
        pageBean.setPageSize(Integer.parseInt(map.get("pageSize")+""));
        pageBean.setTotalNum((int) pageInfo.getTotal());
        pageBean.setTotalPageSize(pageInfo.getPages());
        pageBean.setDatas(pageInfo.getList());
        return pageBean;
    }

    public List<Map<String,String>> getCloseValue(){
        return mobileQueueMapper.getCloseValue();
    }

    public List<QueueUser> queueUserList(){
       return mobileQueueMapper.queueUserList();
    }

    public AjaxJson todayManager(){
        List<HashMap<String, Object>> hashMaps = mobileQueueMapper.todayManager();
        List<String> xvalue =  new ArrayList<>();
        List<Integer> yvalue =  new ArrayList<>();
        for(HashMap<String, Object> mm : hashMaps){
            xvalue.add((String) mm.get("office"));
            yvalue.add((Integer) mm.get("value"));
        }
        hashMaps.clear();
        return AjaxJson.success().put("xvalue",xvalue).put("yvalue",yvalue);
    }

    public MobileOtherHQueue findUserByQueueId(String id){
        return mobileQueueMapper.findUserByQueueId(id);
    }

    public int findCountCounter(String id){
        return mobileQueueMapper.findCountCounter(id);
    }

    public List<FCJJDQueueEntity> fcjjdQueueInfo(String startTime,String endTime){
        return mobileQueueMapper.fcjjdQueueInfo(startTime,endTime);
    }
    @Transactional(readOnly = false)
    public int intoRCUser(String idcard){
        return mobileQueueMapper.intoRCUser(idcard);
    }

    public String findTypeNo(String areaId,String typeNo){
        return mobileQueueMapper.findTypeNo(areaId,typeNo);
    }


    public List<Map<String,Object>> cdszwphgetOrgrizeTree(){
        return mobileQueueMapper.cdszwphgetOrgrizeTree();
    }
    public String getOrgrizeId(String itemCode){
        return mobileQueueMapper.getOrgrizeId(itemCode);
    }
    public List<Map<String,String>> cdszwphyw(String itemCode){
        return mobileQueueMapper.cdszwphyw(itemCode);
    }
    public List<Map<String,String>> cdszwphywchildren(String itemCode){ return mobileQueueMapper.cdszwphywchildren(itemCode); }
    public List<Map<String,Object>> cdszwphgetQuHua(){ return mobileQueueMapper.cdszwphgetQuHua(); }

    public List<Map<String,Object>> cdszwphgetSpot(){
        return mobileQueueMapper.cdszwphgetSpot();
    }
    public List<Map<String,Object>> cdszwphgetClassification(String spotCode){
        return mobileQueueMapper.cdszwphgetClassification(spotCode);
    }
    public List<Map<String,Object>> cdszwphgetBusinessByDepartmentName(String departmentName){
        return mobileQueueMapper.cdszwphgetBusinessByDepartmentName(departmentName);
    }
    public List<Map<String,Object>> cdszwphgetBusiness(String spotCode){
        return mobileQueueMapper.cdszwphgetBusiness(spotCode);
    }
    public Map<String,String> cdszwphgetSpotBySpotCode(String spotCode){
        return mobileQueueMapper.cdszwphgetSpotBySpotCode(spotCode);
    }
    public Map<String,String> cdszwphgetClassificationByitemCodeItemCode(String itemCode){
        return mobileQueueMapper.cdszwphgetClassificationByitemCodeItemCode(itemCode);
    }
    public Boolean findDoTime(String typeId){
        String doTime = mobileQueueMapper.findDoTime(typeId);
        if(StringUtils.isBlank(doTime))return false;
        else {
            String[] split = doTime.split("-");
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
            Date time = new Date();
            List <Integer> integers = mobileQueueMapper.checkDoTime(sd.format(time) + " " + split[0], sd.format(time) + " " + split[1]);
            if(integers.get(0) >= 0 && integers.get(1) <= 0) return true;
            else return false;
        }
    }

    public PageBean<PJQueue> findAllPJ(String areaId,String wino,String pj,String number,String pageNo,String pageSize,String beginWorkTime,String endWorkTime){
        PageBean<PJQueue> pageBean = new PageBean<>();
        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        List<PJQueue> list = mobileQueueMapper.findAllPJ(areaId,wino,pj,number,beginWorkTime,endWorkTime);
        PageInfo<PJQueue> pageInfo = new PageInfo<>(list);
        pageBean.setCrurentNum(Integer.parseInt(pageNo));
        pageBean.setPageSize(Integer.parseInt(pageSize));
        pageBean.setTotalNum((int) pageInfo.getTotal());
        pageBean.setTotalPageSize(pageInfo.getPages());
        pageBean.setDatas(pageInfo.getList());
        return pageBean;
    }

    public Map<String,String> findNumberValue(String area,String number){
        return mobileQueueMapper.findNumberValue(area,number);
    }
}
